package com.lilihub.miaosha.service;

import com.lilihub.miaosha.dao.OrderDao;
import com.lilihub.miaosha.domain.MiaoshaOrder;
import com.lilihub.miaosha.domain.MiaoshaUser;
import com.lilihub.miaosha.domain.OrderInfo;
import com.lilihub.miaosha.redis.OrderKey;
import com.lilihub.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @BelongsProject: miaosha
 * @BelongsPackage: com.lilihub.miaosha.service
 * @Author: LiYing
 * @CreateTime: 2021-04-27 11:25
 * @Description:
 */
@Service
public class OrderService {


    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisService redisService;

    //判断用户是否已经秒杀到了
    public MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(Long userId, long goodsId) {
        //从缓存中查看是否有数据
        return redisService.get(OrderKey.getMiaoshaOrderByUidGid, ""+userId+"_"+goodsId, MiaoshaOrder.class);
//       return orderDao.getMiaoshaOrderByUserIdGoodsId(userId,goodsId);
    }

    //下订单  order_info,miaosha_order
    @Transactional
    public OrderInfo createOrder(MiaoshaUser user, GoodsVo goods) {

        //order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);   //可以使用枚举类表示
        orderInfo.setUserId(user.getId());
        orderDao.insert(orderInfo);

       //miaosha_order
       MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
       miaoshaOrder.setUserId(user.getId());
       miaoshaOrder.setGoodsId(goods.getId());
       miaoshaOrder.setOrderId(orderInfo.getId());

        orderDao.insertMiaoshaOrder(miaoshaOrder);

        //生成订单后，将订单的信息放入到缓存中
        redisService.set(OrderKey.getMiaoshaOrderByUidGid, ""+user.getId()+"_"+goods.getId(),miaoshaOrder);

        return orderInfo;

    }

    public OrderInfo getOrderById(long orderId) {

        return orderDao.getOrderById(orderId);

    }

    @Transactional
    public void deletOrders() {

        orderDao.deleteorderInfo();
        orderDao.deleteMiaoshaOrders();

    }
}
